package com.maker.service.impl;

import com.maker.entity.OrderInfo;
import com.maker.entity.Product;
import com.maker.enums.OrderStatus;
import com.maker.enums.PayType;
import com.maker.service.OrderInfoRepository;
import com.maker.service.ProductRepository;
import com.maker.utils.OrderNoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class OrderInfoService {

    @Resource
    private OrderInfoRepository orderInfoRepository;
    @Resource
    private ProductRepository productRepository;
    ////先查询订单是否存在
    public OrderInfo verifyOrderIsExist(Long  productId){

        OrderInfo orderInfo = new OrderInfo();
        //先查询订单是否存在
        List<OrderInfo> orderInfos = orderInfoRepository.getOrderInfoByProductId(productId, OrderStatus.NOTPAY.getType(), 11L);
        if(!CollectionUtils.isEmpty(orderInfos)){
            log.info("已存在订单，不需要创建");
            return orderInfos.get(0);
        }
        //获取商品信息
        Product product = productRepository.getById(productId);

        orderInfo.setTitle(product.getTitle());
        orderInfo.setOrderNo(OrderNoUtils.getOrderNo());
        orderInfo.setUserId(11L);
        orderInfo.setProductId(productId);
        orderInfo.setTotalFee(product.getPrice());
        orderInfo.setOrderStatus(OrderStatus.NOTPAY.getType());
        Timestamp now = new Timestamp(System.currentTimeMillis());
        orderInfo.setCreateTime(now);
        orderInfo.setPaymentType(PayType.ALIPAY.getType());
        orderInfoRepository.save(orderInfo);
        log.info("创建新订单");
        return orderInfo;
    }

    /**
     * 查询创建简单超过minutes分钟并且未被支付的订单
     * @param minutes
     * @return
     */
    public List<OrderInfo> getNoPayOrderByDuration(int minutes){

        Instant instant = Instant.now().minus(Duration.ofMinutes(minutes));
        Date date = Date.from(instant);
        List<OrderInfo> orderInfos = orderInfoRepository.getNoPayOrderByDuration(date, OrderStatus.NOTPAY.getType(),PayType.ALIPAY.getType());
        return   orderInfos;
    }

    /**
     * 查询创建简单超过minutes分钟并且未被支付的订单
     * @param minutes
     * @return
     */
    public List<OrderInfo> getPayOrderByDuration(int minutes){

        Instant instant = Instant.now().minus(Duration.ofMinutes(minutes));
        Date date = Date.from(instant);
        List<OrderInfo> orderInfos = orderInfoRepository.getNoPayOrderByDuration(date, OrderStatus.SUCCESS.getType(),PayType.ALIPAY.getType());
        return   orderInfos;
    }






}
